<?php

use App\Models\AdministrativeDivision;
use App\Models\Flow;
use Carbon\Carbon;

function get_hls_link($channel_id=null){
    if ($channel_id!=null)
        return str_replace('{channel_id}', $channel_id, config('hls_link'));
    return false;

}
function get_rtmp_link($channel_id=null){
    if ($channel_id!=null)
        return str_replace('{channel_id}', $channel_id, config('rtmp_link'));
    return false;
}
function get_monitor_cover($channel_id=null){
    if ($channel_id!=null)
        return str_replace('{channel_id}', $channel_id, config('monitor_cover'));
    return false;
}
function get_monitor_list($channel_ids=array()){
    if (!empty($channel_ids)&&count($channel_ids)>0){
        $list =[];
        foreach ($channel_ids as $k=>$v){
            $list[$k]['hls'] = get_hls_link($v);
            $list[$k]['rtmp'] = get_rtmp_link($v);
            $list[$k]['cover'] = get_monitor_cover($v);
        }
        return $list;
    }
    return false;
}
function get_sys_status(){

    return array(
        'sys'=>php_uname(),
        'memory'=>memory_get_usage(),
        'cpu'=>getrusage(),
        'disk'=>disk_free_space('/')/disk_total_space('/')
    );
}
function get_flow($scene_id=null){
    $today=Carbon::today()->toDateString();
    $yesterday= Carbon::yesterday()->toDateString();
    if($scene_id==null){
        $today = Flow::where('date',$today)->where('time','<>',0)->sum('num');
        $yesterday = Flow::where('date',$yesterday)->where('time',0)->sum('num');
    }else{
        $today=Flow::where([
            ['date',$today],
            ['scene_id',$scene_id]
        ])->where('time','<>',0)->sum('num');
        $yesterday = Flow::where([
            ['date',$yesterday],
            ['scene_id',$scene_id]
        ])->where('time',0)->sum('num');
    }
    return array(
        'today'=>$today,
        'yesterday'=>$yesterday,
    );
}
function get_age($id_code){
    if(strlen($id_code)>=8)
        $birthday = substr($id_code,6,8);
    else
        $birthday=$id_code;
    return substr(date('Ymd')-$birthday,0,2);
}
function get_source($id_code){
    if(strlen($id_code)>=15){
        $code = substr($id_code,0,6);
        if(!empty($id_code)||count($id_code)>=0){
                $address = AdministrativeDivision::select(['province','city','county'])->where('code_six',substr($code,0,6))->first();
        }else{
            $address=['province'=>'境外'];
        }
        return $address;
    }else{
        return ['province'=>'境外'];
    }
}

/**
 * POST请求https接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $post [请求的参数]
 * @return  string
 */
function post_curls($url, $post=[],$headers=[],$https = true)
{
//    if(!empty($post)){
//        $data = '';
//        foreach ($post as $key=>$val){
//            $data.=$key.'='.$val.'&';
//        }
//        $url = $url.'?'.$data;
//    }
    $res = null;
    $curl = curl_init(); // 启动一个CURL会话
    try{
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if($https){
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        //请求头定义为json数据
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        $res = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return curl_error($curl);//捕抓异常
        }
    }catch (Exception $exception){

    }finally{
        curl_close($curl); // 关闭CURL会话
    }
    return json_decode($res,true); // 返回数据，json格式
}
function get_dh_token(){
    $url = env('DH_GET_TOKEN_URL');
    $data = array('client_id'=>env('DH_CLIENT_ID'),'client_secret'=>env('DH_CLIENT_SECRET'),'grant_type'=>'client_credentials','scope'=>'server');
    $headers = array('Content-Type'=>'application/x-www-form-urlencoded');
    return post_curls($url,$data,$headers,false);
}

function getDHToken($clientid , $secret){
    $url = 'http://www.cloud-dahua.com:8088/gateway/auth/oauth/token?grant_type=client_credentials&scope=server&client_id='.$clientid.'&client_secret='.$secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    $output = curl_exec($ch);//获取数据
    curl_close($ch);//关闭curl
    return $output;
}

function getDHuserToken($token ,$phone){
    $url = 'http://www.cloud-dahua.com:8088/gateway/device/lechange/getUserToken';
    $post_data  = array(
        'telephone' => $phone
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $header = ['Authorization: Bearer '.$token,'Content-Type:application/json;charset=utf-8'];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
    $output = curl_exec($ch);//获取数据
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($output, 0, $headerSize);
    $body = substr($output, $headerSize);
    curl_close($ch);//关闭curl
    return $body;
}

function createDHdevice($dhkoten , $token , $deviceid , $channel , $stream = '0' , $livemode = 'cdn'){
    $url = 'https://www.cloud-dahua.com/gateway/device/api/deviceLive';
    $post_data  = array(
        'token'    => $token,
        'deviceId' => $deviceid,
        'channelId'=> $channel,
        'streamId' => $stream,
        'liveMode' => $livemode
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $header = ['Authorization: Bearer '.$dhkoten,'Content-Type:application/json;charset=utf-8'];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
    $output = curl_exec($ch);//获取数据

    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($output, 0, $headerSize);
    $body = substr($output, $headerSize);

    curl_close($ch);//关闭curl
    return $body;
}

function getDHdeviceList($dhtoken , $token){

    $url = 'https://www.cloud-dahua.com/gateway/device/api/liveList';
    $post_data  = array(
        'token'     => $token,
        'queryRange'=> '1-100'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $header = ['Authorization: Bearer '.$dhtoken,'Content-Type:application/json;charset=utf-8'];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
    $output = curl_exec($ch);//获取数据
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($output, 0, $headerSize);
    $body = substr($output, $headerSize);

    curl_close($ch);//关闭curl
    return $body;
}

function getWjgjVideo(){
    $url = 'http://v.weijingguanjia.com:10800/api/v1/getchannels';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $output = curl_exec($ch);//获取数据
    curl_close($ch);//关闭curl
    $output = json_decode($output);
    $vlist = [];
    if(property_exists($output, 'EasyDarwin')){
        $list = $output->EasyDarwin->Body->Channels;
        foreach ($list as $v){
            $vo['channel']= $v->Channel;
            $vo['status'] = $v->Online;
            $vo['cover'] = $v->SnapURL;
            $vlist[] = $vo;
            unset($vo);
        }
    }else{
        $vlist = [];
    }
    return $vlist;
}